package com.szdxh.license.util;

/**
 * @author 双子的小坏
 * @date 2024/7/3 10:18:42
 * @description :
 */

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class RedisUtil {

    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置指定键的值。
     *
     * @param key 键
     * @param value 值
     */
    public void set(String key, Object value) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        ops.set(key, value);
    }

    /**
     * 使用过期时间设置指定键的值。
     *
     * @param key 键
     * @param value 值
     * @param timeout 有效期
     * @param unit 有效期单位
     */
    public void set(String key, Object value, long timeout, TimeUnit unit) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        ops.set(key, value, timeout, unit);
    }

    /**
     * 根据key获取value.
     *
     * @param key the key
     * @return the value
     */
    public Object get(String key) {
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        return ops.get(key);
    }

    /**
     * 根据key进行删除.
     *
     * @param key the key
     * @return true if the key was removed, false otherwise
     */
    public boolean delete(String key) {
        return Boolean.TRUE.equals(redisTemplate.delete(key));
    }

    /**
     * 检查key是否存在.
     *
     * @param key the key
     * @return true if the key exists, false otherwise
     */
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }
}
